package com.javasm.duanju.service.impl;

import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.FileInfo;
import com.qiniu.util.Auth;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;

@Service
public class QiNiuService implements InitializingBean {

    @Value("${qiniu.accessKey}")
    private String accessKey;

    @Value("${qiniu.secretKey}")
    private String secretKey;

    @Value("${qiniu.bucketName}")
    private String bucketName;

    @Value("${qiniu.domain}")
    private String domain;

    private BucketManager bucketManager;



    public String getToken() {
        Auth auth = Auth.create(accessKey, secretKey);
        String token = auth.uploadToken(bucketName);
        return token;
    }

    /**
     * 上传文件
     * @param file 文件
     * @param fileName 文件在oss上的路径
     * @return
     */
    public String upload(File file, String fileName) {
        if (file == null) {
            throw new IllegalArgumentException("文件不能为空");
        }
        Configuration cfg = new Configuration(Region.huanan());
        cfg.resumableUploadAPIVersion = Configuration.ResumableUploadAPIVersion.V2;
        UploadManager uploadManager = new UploadManager(cfg);
        String upToken = getToken();
        try {
            Response response = uploadManager.put(file,fileName,upToken);
            System.out.println(response.bodyString());
            //解析上传成功的结果
//            DefaultPutRet putRet = JSON.parseObject(response.bodyString(), DefaultPutRet.class);
            return fileName;
        } catch (Exception ex) {
            System.out.println("OSS上传失败");
        }
        return null;
    }

    public String upload(MultipartFile multipartFile, String path) {
        if (multipartFile == null) {
            return null;
        }
        Configuration cfg = new Configuration(Region.huanan());
        cfg.resumableUploadAPIVersion = Configuration.ResumableUploadAPIVersion.V2;
        UploadManager uploadManager = new UploadManager(cfg);
        String upToken = getToken();
        try {
            Response response = uploadManager.put(multipartFile.getInputStream(), path, upToken, null, null);
            //解析上传成功的结果
//            DefaultPutRet putRet = JSON.parseObject(response.bodyString(), DefaultPutRet.class);
            return path;
        } catch (Exception ex) {
            System.out.println("OSS上传失败"+ ex.getMessage());
        }
        return null;
    }

    public String move(String sourceFile, String targetFile) {
        try {
            Response response = bucketManager.move(bucketName, sourceFile, bucketName, targetFile,true);
            return targetFile;
        } catch (Exception ex) {
            System.out.println("OSS移动文件失败"+ ex.getMessage());
        }
        return null;
    }

    public void deleteFile(String filePath) {
        try {
            Response response = bucketManager.delete(bucketName, filePath);
        } catch (Exception ex) {
            System.out.println("OSS删除文件失败"+ ex.getMessage());
        }
    }

    public void deleteFolder(String folderPath) {
        try {
            String[] fileList = null;
            BucketManager.FileListIterator fileListIterator = bucketManager.createFileListIterator(bucketName, folderPath);
            while (fileListIterator.hasNext()) {
                //处理获取的file list结果
                FileInfo[] items = fileListIterator.next();
                fileList = new String[items.length];
                for (int i = 0; i < items.length; i++) {
                    fileList[i] = items[i].key;
                }
            }
            if(fileList != null && fileList.length > 0){
                BucketManager.BatchOperations batchOperations = new BucketManager.BatchOperations();
                batchOperations.addDeleteOp(bucketName, fileList);
                Response response = bucketManager.batch(batchOperations);
                System.out.println(response.bodyString());
            }
        } catch (Exception ex) {
            System.out.println("OSS删除文件失败"+ ex.getMessage());
        }
    }

    public static void main(String[] args) {
        Configuration cfg = new Configuration(Region.huanan());
        cfg.resumableUploadAPIVersion = Configuration.ResumableUploadAPIVersion.V2;
        Auth auth = Auth.create("npEUaLPu-s6p2by3ZKWFLQ9W9jE5s4QzhbSVZ9G8", "b28Y0ysuTCp24WvOnTmGg-dQfBM0HBSsfSIBE2eW");
        BucketManager bucketManager = new BucketManager(auth, cfg);
        try {
            String[] fileList = null;
            BucketManager.FileListIterator fileListIterator = bucketManager.createFileListIterator("javasmcd", "dj/video/1000601/1000000371/");
            while (fileListIterator.hasNext()) {
                //处理获取的file list结果
                FileInfo[] items = fileListIterator.next();
                fileList = new String[items.length];

                for (int i = 0; i < items.length; i++) {
                    fileList[i] = items[i].key;
                }
            }
            BucketManager.BatchOperations batchOperations = new BucketManager.BatchOperations();
            batchOperations.addDeleteOp("javasmcd", fileList);
            Response response = bucketManager.batch(batchOperations);
            System.out.println(response.bodyString());
        } catch (Exception ex) {
            System.out.println("OSS删除文件失败"+ ex.getMessage());
        }

    }

    @Override
    public void afterPropertiesSet() throws Exception {
        Configuration cfg = new Configuration(Region.huanan());
        cfg.resumableUploadAPIVersion = Configuration.ResumableUploadAPIVersion.V2;
        Auth auth = Auth.create(accessKey, secretKey);
        this.bucketManager = new BucketManager(auth, cfg);
    }
}
